<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

/**
 * Class RunGameLogs
 * @package App
 */
class RunGameLogs extends Model
{
    public $timestamps = false;
    protected $table = "run_game_logs";

    const STATUS_OFF = 0;
    const STATUS_ON = 1;

    const SHARE_NO = 0;
    const SHARE_YES = 1;
    /**
     * @return array
     */
    static function Today()
    {
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        return [$beginToday, $endToday];
    }


    /**
     * 开始游戏出题
     * @param $user_id
     * @return array
     */
    static function SendQuestion($user_id)
    {
        $config = DB::table('run_game_config')->select('items_num', 'game_times')->find(1);
        //建立今天的游戏记录
        if (!$log_id = RunGameLogs::whereBetween('start_at', RunGameLogs::Today())->where('user_id', $user_id)->value('id')) {
            $gameLog = new RunGameLogs();
            $gameLog->user_id = $user_id;
            $gameLog->season_id = RunGameSeason::ThisSeason();
            $gameLog->times = $config->game_times;
            $gameLog->start_at = time();
            if (!$gameLog->save()) {
                return error('游戏开始失败');
            }
            $log_id = $gameLog->id;
        }

        //筛选出来以前答过的题目
        $answered = RunGameLogs::where('user_id', $user_id)->pluck('item_ids')->toArray();
        $answered = explode(',', join(',', $answered));
        //没答过的题
        $items_no = RunGameItems::select('id', 'title', 'answer')->whereNotin('id', $answered)->get()->toArray();
        if (count($items_no) < $config->items_num) {
            $items_no = RunGameItems::select('id', 'title', 'answer')->get()->toArray();
        }
        //乱序，取前十题
        shuffle($items_no);
        $items = array_slice($items_no, 0, $config->items_num);
        return success(compact('items', 'log_id'));
    }


    /**
     * 结束游戏
     * @param $user_id
     * @param $integral
     * @return array
     * @throws \Exception
     */
    static function EndGame($user_id, $integral)
    {
        $time = time();
        $before = RunGameRank::SelfRank($user_id);
        DB::beginTransaction();

        $noviceTask = NoviceTaskRecord::RecordPublish($user_id, NoviceTaskRecord::TYPE_RUNGAMINNG);
        if ($noviceTask['status'] !== 1) {
            DB::rollBack();

            return error('游戏结束失败');
        }

        //排行榜加分
        $rank = RunGameRank::AddRank($user_id, $integral);
        if ($rank['code'] !== 200) {
            DB::rollBack();

            return $rank;
        }

        //游戏结束
        $gameLog = RunGameLogs::find(request('log_id'));
        $gameLog->item_ids = $gameLog->item_ids ? $gameLog->item_ids . ',' . request('item_ids') : request('item_ids');
        $gameLog->integral = $gameLog->integral + $integral;
        $gameLog->end_at = time();
        $gameLog->times = $gameLog->times - 1;
        if (!$gameLog->save()) {
            DB::rollBack();

            return error('游戏结束失败');
        }
        $integral_pre = DB::table('run_game_config')->value('integral_pre');
        $season_id = RunGameSeason::ThisSeason();
        $season_title = RunGameSeason::where('id', $season_id)->value('title');
        //发放金币
        $price_insert = [
            'user_id' => $user_id,
            'season_id' => $season_id,
            'reward_id' => 0,
            'status' => 4,
            'number' => $integral * $integral_pre,
            'created_at' => $time,
            'updated_at' => $time,
        ];
        if (!RunGamePrize::insert($price_insert)) {
            DB::rollBack();

            return error('金币发放失败');
        }
        //收益记录
        $operation_insert = [
            'type' => 5,
            'number' => '+'.$integral * $integral_pre.'金币',
            'name' => '游戏',
            'status' => 2,
            'user_id' => $user_id,
            'create_time' => date('Y-m-d H:i:s', $time),
            'reflect_type' => 1,
            'reflect_name' => '跑步游戏',
            'transaction_time' => date('Y-m-d H:i:s', $time),
        ];
        if (!DB::table('operation_record')->insert($operation_insert)) {
            DB::rollBack();

            return error('收益记录添加失败');
        }

        if ($integral) {
            //增加金币
            if (!DB::table('t_member')->where('c_id', $user_id)->increment('coin_number', $integral * $integral_pre)) {
                DB::rollBack();

                logger('金币发放失败');
                return error('金币发放失败');
            }
            $push_insert = [
                'title' => '系统消息',
                'content' => "您在健康大闯关游戏{$season_title}赛季获得了参与奖，答对题数的金币已经到账",
                'ctime' => date('Y-m-d H:i:s', $time),
                'user_id' => $user_id
            ];
            if (!DB::table('jpush')->insert($push_insert)) {
                DB::rollBack();

                logger('发送消息失败');
                return error('发送消息失败');
            }
            Curl::PushOne($push_insert['user_id'], $push_insert['content']);
        }
        DB::commit();
        $after = RunGameRank::SelfRank($user_id);

        $meaasge = '游戏结束';
        $overstap = $before-$after;
        return success(compact('meaasge', 'overstap'));
    }


    /**
     * 添加游戏次数
     * @param $log_id
     * @return array
     */
    static function AddTimes($log_id)
    {
        $log = RunGameLogs::find($log_id);
        $log->times = $log->times+1;
        $log->has_share = self::SHARE_YES;
        if (!$log->save()) {
            return error();
        }
        return success();
    }

    /**
     * 添加游戏次数并新建数据
     * @param $user_id
     * @return array
     */
    static function NewAddTimes($user_id)
    {
        $gameLog = new RunGameLogs();
        $gameLog->user_id = $user_id;
        $gameLog->season_id = RunGameSeason::ThisSeason();
        $gameLog->start_at = time();
        $gameLog->times = 2;
        $gameLog->has_share = self::SHARE_YES;
        if (!$gameLog->save()) {
            return error();
        }
        return success();
    }
}
